from fastapi import APIRouter, Query
from app.controllers.exams.user_answer import user_answer_controller
from app.core.dependency import DependCustomerAuth
from app.core.ctx import CTX_USER_ID
from app.models import Exam
from app.schemas.exams import UserAnswerCreate, UserAnswerUpdate
from app.schemas.base import Success, SuccessExtra,Fail
from app.models.customer import CustomerUser,CustomerLevel
from tortoise.expressions import Q

user_answer_router = APIRouter()


@user_answer_router.post("/create", summary=f"生成试卷答案",dependencies=[DependCustomerAuth])
async def do_create(
        data_in: UserAnswerCreate,
):
    await user_answer_controller.do_create(obj_in=data_in)
    return Success(msg="创建成功")


@user_answer_router.post("/update", summary=f"更新试卷")
async def do_update(
        category_in: UserAnswerUpdate,
):
    await user_answer_controller.do_update(obj_in=category_in)
    return Success(msg="更新成功")

@user_answer_router.delete("/delete", summary=f"删除试卷")
async def do_delete(
        data_id: int = Query(..., description="ID"),
):
    await user_answer_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")

@user_answer_router.get("/list", summary=f"查看试卷列表")
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        title: str = Query(None, description=f"名称"),
        user_name: str = Query(None, description=f"用户昵称"),
):
    q = Q()

    search_exam_id = []
    search_user_id = []
    if title:
        search_exam = await Exam.filter(title__contains=title).values("id")
        search_exam_id = {exam['id'] for exam in search_exam}  # 获取所有的 goods_id
    if user_name:
        search_user = await CustomerUser.filter(name__contains=user_name).values("id")
        search_user_id= {user['id'] for user in search_user}  # 获取所有的 goods_id

    if search_exam_id:
        q &= Q(exam_id__in=search_exam_id)
    if search_user_id:
        q &= Q(user_id__in=search_user_id)
    total, data = await user_answer_controller.do_list(page=page, page_size=page_size, search=q)
    user_ids = {itm['user_id'] for itm in data}  # 获取所有的用户
    exam_ids = {itm['exam_id'] for itm in data}  # 获取所有的用户
    users = await CustomerUser.filter(id__in=user_ids)
    exams = await Exam.filter(id__in=exam_ids)
    users_dict = {user.id: user.name for user in users}
    exams_dict = {exam.id: exam.title for exam in exams}
    print(exams_dict)
    for item in data:
        item['user_name'] = users_dict.get(item['user_id'], "默认用户")
        item['title'] = exams_dict.get(item['exam_id'], "无试卷")
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)